package com.example.demo.util;

import com.example.demo.web.BaseController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * <p>
 * 重置 UEditor 访问路径
 * </p>
 * ***********************************************
 * BECAUSE OF CHOICE, STICK TO IT.               *
 * ***********************************************
 */
@RestController
@CrossOrigin
@RequestMapping("UEditor")
public class UEditorController extends BaseController {

    private static final Logger LOG = LogManager.getLogger(UEditorController.class);

    @RequestMapping("")
    private String showPage(HttpServletRequest request) throws UnsupportedEncodingException, JSONException {
        request.setCharacterEncoding("utf-8");
        String rootPath = new File (request.getSession().getServletContext().getRealPath("/")).getParent();
        //return new ActionEnter(request, rootPath).exec();
        ActionEnter actionEnter = new ActionEnter(request, rootPath);
        return actionEnter.getConfigManager().getJsonConfig().toString();
    }

    @RequestMapping("config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        LOG.debug(rootPath);
        try {
            //String exec = new ActionEnter(request, rootPath).exec();
            String exec = new ActionEnter(request, rootPath).getConfigManager().getJsonConfig().toString();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }
}
